package com.rmy.publish.service.impl;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import ch.qos.logback.core.util.FileUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.util.UUIDUtils;
import com.rmy.common.config.RmyConfig;
import com.rmy.common.core.lang.IdGenerator;
import com.rmy.common.exception.ServiceException;
import com.rmy.common.utils.DateUtils;
import com.rmy.common.utils.file.FileExtUtils;
import com.rmy.common.utils.file.FileUtils;
import com.rmy.publish.domain.MipsControllerInfo;
import com.rmy.publish.domain.MipsPageInfo;
import com.rmy.publish.service.IMipsControllerInfoService;
import com.rmy.publish.service.IMipsPageInfoService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.rmy.publish.mapper.MipsProgramInfoMapper;
import com.rmy.publish.domain.MipsProgramInfo;
import com.rmy.publish.service.IMipsProgramInfoService;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 节目管理Service业务层处理
 *
 * @author rmy
 * @date 2023-05-21
 */
@Service
public class MipsProgramInfoServiceImpl implements IMipsProgramInfoService
{
    @Autowired
    private MipsProgramInfoMapper mipsProgramInfoMapper;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private IMipsPageInfoService mipsPageInfoService;

    @Autowired
    private IMipsControllerInfoService mipsControllerInfoService;

    private String TEMP_JSON = "template.json";

    /**
     * 查询节目管理
     *
     * @param programId 节目管理主键
     * @return 节目管理
     */
    @Override
    public MipsProgramInfo selectMipsProgramInfoByProgramId(Long programId)
    {
        return mipsProgramInfoMapper.selectMipsProgramInfoByProgramId(programId);
    }

    @Override
    public MipsProgramInfo selectMipsProgramInfoByProgramCode(String programCode) {
        return mipsProgramInfoMapper.selectMipsProgramInfoByProgramCode(programCode);
    }

    /**
     * 查询节目管理列表
     *
     * @param mipsProgramInfo 节目管理
     * @return 节目管理
     */
    @Override
    public List<MipsProgramInfo> selectMipsProgramInfoList(MipsProgramInfo mipsProgramInfo)
    {
        return mipsProgramInfoMapper.selectMipsProgramInfoList(mipsProgramInfo);
    }

    /**
     * 新增节目管理
     *
     * @param mipsProgramInfo 节目管理
     * @return 结果
     */
    @Override
    public int insertMipsProgramInfo(MipsProgramInfo mipsProgramInfo)
    {
        mipsProgramInfo.setProgramCode(idGenerator.nextIdStr());
        mipsProgramInfo.setCreateTime(DateUtils.getNowDate());
        return mipsProgramInfoMapper.insertMipsProgramInfo(mipsProgramInfo);
    }

    /**
     * 修改节目管理
     *
     * @param mipsProgramInfo 节目管理
     * @return 结果
     */
    @Override
    public int updateMipsProgramInfo(MipsProgramInfo mipsProgramInfo)
    {
        mipsProgramInfo.setUpdateTime(DateUtils.getNowDate());
        return mipsProgramInfoMapper.updateMipsProgramInfo(mipsProgramInfo);
    }

    /**
     * 批量删除节目管理
     *
     * @param programIds 需要删除的节目管理主键
     * @return 结果
     */
    @Override
    public int deleteMipsProgramInfoByProgramIds(Long[] programIds)
    {
        return mipsProgramInfoMapper.deleteMipsProgramInfoByProgramIds(programIds);
    }

    /**
     * 删除节目管理信息
     *
     * @param programId 节目管理主键
     * @return 结果
     */
    @Override
    public int deleteMipsProgramInfoByProgramId(Long programId)
    {
        return mipsProgramInfoMapper.deleteMipsProgramInfoByProgramId(programId);
    }

    @Override
    public int insertProgram(MipsProgramInfo mipsProgramInfo) {
        int nRet = 0;
        // 0. 根据节目编码查询节目信息
        MipsProgramInfo resProgramInfo = mipsProgramInfoMapper.selectMipsProgramInfoByProgramCode(mipsProgramInfo.getProgramCode());
        Assert.notNull(resProgramInfo, "未找到【"+mipsProgramInfo.getProgramCode()+"】的节目信息");
        // 1. 根据节目编号查询所有页面
        MipsPageInfo reqPageInfo = new MipsPageInfo();
        reqPageInfo.setProgramId(resProgramInfo.getProgramId());
        List<MipsPageInfo> mipsPageInfoList = mipsPageInfoService.selectMipsPageInfoList(reqPageInfo);
        // 2. 根据页面pageId删除控件表中所有的记录及页面表中的所有数据
        for (MipsPageInfo pageInfo : mipsPageInfoList) {
            nRet = mipsControllerInfoService.deleteMipsControllerInfoByPageId(pageInfo.getPageId());
            nRet = mipsPageInfoService.deleteMipsPageInfoByPageId(pageInfo.getPageId());
        }
        // 3. 循环重新插入页面信息表
        for (MipsPageInfo pageInfo : mipsProgramInfo.getPageInfoList()) {
            pageInfo.setProgramId(resProgramInfo.getProgramId());
            nRet = mipsPageInfoService.insertMipsPageInfo(pageInfo);
            // 4. 循环插入控件信息表
            for (MipsControllerInfo controllerInfo : pageInfo.getControllerInfoList()) {
                JSONObject jValue = controllerInfo.getValue();
                controllerInfo.setPageId(pageInfo.getPageId());
                controllerInfo.setControllerType(controllerInfo.getType());
                controllerInfo.setData(jValue != null ? jValue.getString("data"): "");
                controllerInfo.setPos(jValue != null ? jValue.getString("pos"): "");
                controllerInfo.setSetting(jValue != null ? jValue.getString("setting"): "");
                nRet = mipsControllerInfoService.insertMipsControllerInfo(controllerInfo);
            }
        }

        return nRet;
    }



    @Override
    public void exportProject(HttpServletRequest request, HttpServletResponse response, String programCode, Integer showDataSet) throws IOException {
        String userAgent = request.getHeader("User-Agent");
        boolean isIeBrowser = userAgent.indexOf("MSIE") > 0;
        MipsProgramInfo mipsProgramInfo = selectMipsProgramInfoByProgramCode(programCode);

        // check 所有资源是否可以正常发布 需要审核的弹出提示 TODO

        String filePath = RmyConfig.getDownloadPath();
        // 组装临时文件夹路径
        String path = filePath + idGenerator.nextIdStr();
        Assert.notNull(mipsProgramInfo, "未找到节目编码["+programCode+"]对应的节目");
        Assert.notEmpty(mipsProgramInfo.getPageInfoList(), "节目["+programCode+"]尚未配置页面");
        // 创建临时文件夹
        FileExtUtils.createAllDirectories(path);

        // 循环取页面的背景图
        for (int i = 0; i < mipsProgramInfo.getPageInfoList().size(); i++) {
            MipsPageInfo mipsPageInfo = mipsProgramInfo.getPageInfoList().get(i);
            String fileName = FileExtUtils.downloadFile(mipsPageInfo.getBackgroundImage(), path);
            // 设置为相对路径
            mipsProgramInfo.getPageInfoList().get(i).setBackgroundImage(fileName);
            // 循环控件
            if ( mipsPageInfo.getControllerInfoList() == null ||
                    mipsPageInfo.getControllerInfoList().size() == 0) continue;
            for (int j = 0; j < mipsPageInfo.getControllerInfoList().size(); j++) {
                MipsControllerInfo mipsControllerInfo = mipsPageInfo.getControllerInfoList().get(j);
                if ("image-controller".equals(mipsControllerInfo.getControllerType())) {
                    // 图片
                    JSONObject jSetting = JSONObject.parse(mipsControllerInfo.getSetting());
                    fileName = FileExtUtils.downloadFile(jSetting.getString("imageAdress"), path);
                    jSetting.put("imageAdress", fileName);
                    mipsPageInfo.getControllerInfoList().get(j).setSetting(jSetting.toJSONString());
                } else if ("video-controller".equals(mipsControllerInfo.getControllerType())) {
                    // 视频
                    JSONObject jSetting = JSONObject.parse(mipsControllerInfo.getSetting());
                    fileName = FileExtUtils.downloadFile(jSetting.getString("videoAdress"), path);
                    jSetting.put("videoAdress", fileName);
                    mipsPageInfo.getControllerInfoList().get(j).setSetting(jSetting.toJSONString());
                }
            }
        }

        //2.将大屏设计到的json文件保存
        String jsonPath = path + File.separator + TEMP_JSON;
        FileExtUtils.WriteStringToFile(jsonPath, JSONObject.toJSONString(mipsProgramInfo));

        //将path文件夹打包zip
        String zipPath = path + ".zip";
        FileExtUtils.compress(path, zipPath);


        File file = new File(zipPath);

        byte[] data = FileExtUtils.readFileToByteArray(file);

        //删除zip文件
        file.delete();
        //删除path临时文件夹
        FileExtUtils.delete(path);

        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\""+ programCode +".zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());

    }
}
